/*
 * Copyright (c) 2011 Metrum Research Group LLC. All Rights Reserved.
 *
 * You may use this software under the terms of GPL v3 (http://www.gnu.org/licenses/gpl.html).
 *
 * METRUM RESEARCH GROUP LLC MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
 * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
 * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. METRUM RESEARCH GROUP LLC SHALL NOT BE LIABLE FOR
 * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
 * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
 */

package sumo;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class SessionOutputServlet extends HttpServlet { 
	private static final String NO_CHANGE = "NO_CHANGE";
	private static final String OLD_OUTPUT = "OLD_OUTPUT";
	/**
	 * Need a UID to extend HttpServlet
	 */
	private static final long serialVersionUID = 1234234238L;
	private static int CHAR_LIMIT = SumoPropertyManager.getConfig().getInt("connection.outputCharLimit");			
	public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { 	
		HttpSession theSession = req.getSession();
                String username = (String)theSession.getAttribute("username");
                if(username == null) return;
                boolean outputUpdated = false;	
		ByteArrayOutputStream theOutput = (ByteArrayOutputStream)req.getSession().getAttribute("Output");
		String theString = theOutput.toString();
		theString = SumoUtils.fixROutput(theString);
		if(theString != null && theString.length() > CHAR_LIMIT){theString = theString.substring(theString.length() - CHAR_LIMIT, theString.length());}
		String oldOutput = (String)req.getSession().getAttribute(OLD_OUTPUT);
		if(oldOutput == null || !oldOutput.equals(theString)){
			outputUpdated = true;
		}
		req.getSession().setAttribute(OLD_OUTPUT, theString);
		res.setContentType("text/plain");
	        res.setHeader("Cache-Control", "no-cache");
        	PrintWriter pw = res.getWriter();
		if(outputUpdated)pw.write(theString);
		else pw.write(NO_CHANGE);
        	pw.close();  
	} 
}
